package cuongnh.project.japanesediary.vocabulary.dao;

import java.util.Date;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cuongnh.project.japanesediary.vocabulary.model.Kanji;
import cuongnh.project.japanesediary.vocabulary.model.Vocabulary;

@Repository
@Transactional
public class KanjiDao extends HibernateDaoSupport {

	public void save(Kanji a1) {
		a1.setCreatedDate(new Date());
		a1.setModifiedDate(new Date());
		getHibernateTemplate().save(a1);
	}
	
	public void saveOrUpdate(Kanji a1) {
		a1.setModifiedDate(new Date());
		if(a1.getCreatedDate() == null){
			a1.setCreatedDate(new Date());
		}
		getHibernateTemplate().saveOrUpdate(a1);
	}

	/**
	 * 'load' returns a proxy with only the id populated. To access members in
	 * the proxy requires a Hibernate session. Haven't figured out how to do
	 * transactions between bundles yet...
	 */
	public Kanji load(long id) {
		return (Kanji) getHibernateTemplate().load(Kanji.class, id);
	}

	public Kanji get(long id) {
		return (Kanji) getHibernateTemplate().get(Kanji.class, id);
	}

	public void update(Kanji a1) {
		a1.setModifiedDate(new Date());
		getHibernateTemplate().update(a1);
	}

	/**
	 * Delete current Kanji with all association function
	 * 
	 * @param a1
	 *            : Current Kanji
	 */
	public void delete(Kanji a1) {
		// to avoid conflict with other objects connected (?) with current
		// session
		a1 = load(a1.getKanjiId());
		// initialize lazy set of vocabularies of current Kanji
		getHibernateTemplate().initialize(a1.getCompoundWords());
		// remove association many-to-many with Vocabulary table
		for (Vocabulary vocabulary : a1.getCompoundWords()) {
			vocabulary.getKanjis().remove(a1);
		}

		// delete current Kanji
		getHibernateTemplate().delete(a1);
	}

	public Kanji merge(Kanji a1) {
		a1.setModifiedDate(new Date());
		return (Kanji) getHibernateTemplate().merge(a1);
	}

	public List<Kanji> getAll() {
		return getHibernateTemplate().loadAll(Kanji.class);
	}

	public Kanji getKanjiWithVocabularies(long kanjiId) {
		Kanji kanji = getHibernateTemplate().get(Kanji.class,
				kanjiId);
		getHibernateTemplate().initialize(kanji.getCompoundWords());
		return kanji;
	}
	
	public Kanji getKanjiWithCategories(long kanjiId) {
		Kanji kanji = getHibernateTemplate().get(Kanji.class,
				kanjiId);
		getHibernateTemplate().initialize(kanji.getKanjiCategories());
		return kanji;
	}

	public Kanji getKanjiWithAllLazies(long kanjiId) {
		Kanji kanji = getHibernateTemplate().get(Kanji.class,
				kanjiId);
		getHibernateTemplate().initialize(kanji.getCompoundWords());
		getHibernateTemplate().initialize(kanji.getRadicals());
		return kanji;
	}

}
